<!DOCTYPE html>
<html lang=zh>
<head>
    <!-- so meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="HandheldFriendly" content="True">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5" />
    <meta name="description" content="在研究一个 Promise 之前，我们先来看看没有 Promise 前，存在哪些技术痛点。 没有Promise前遇到的问题网络请求使用的问题在没有出现 Promise 前，如果我们需要发送网络请求，需要封装并且调用这样的函数： 123456789101112function request(url, successCallback, failureCallback) &amp;#123;  &#x2F;&#x2F; 模拟网络">
<meta property="og:type" content="article">
<meta property="og:title" content="Promise">
<meta property="og:url" content="https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/index.html">
<meta property="og:site_name" content="柯里的语法糖">
<meta property="og:description" content="在研究一个 Promise 之前，我们先来看看没有 Promise 前，存在哪些技术痛点。 没有Promise前遇到的问题网络请求使用的问题在没有出现 Promise 前，如果我们需要发送网络请求，需要封装并且调用这样的函数： 123456789101112function request(url, successCallback, failureCallback) &amp;#123;  &#x2F;&#x2F; 模拟网络">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-02-05T06:19:40.050Z">
<meta property="article:modified_time" content="2022-03-16T07:32:05.219Z">
<meta property="article:author" content="柯里的语法糖">
<meta property="article:tag" content="JavaScript">
<meta name="twitter:card" content="summary">
    
    
      
        
          <link rel="shortcut icon" href="https://codertzm.oss-cn-chengdu.aliyuncs.com/favicon.ico">
        
      
      
        
          <link rel="icon" type="image/png" href="https://codertzm.oss-cn-chengdu.aliyuncs.com/favicon.ico" sizes="192x192">
        
      
      
        
          <link rel="apple-touch-icon" sizes="180x180" href="https://codertzm.oss-cn-chengdu.aliyuncs.com/favicon.ico">
        
      
    
    <!-- title -->
    <title>Promise</title>
    <!-- styles -->
    
<link rel="stylesheet" href="/css/style.css">

    <!-- persian styles -->
    
    <!-- rss -->
    
    
	<!-- mathjax -->
	
<meta name="generator" content="Hexo 6.0.0"></head>

<body class="max-width mx-auto px3 ltr">
    
      <div id="header-post">
  <a id="menu-icon" href="#" aria-label="Menu"><i class="fas fa-bars fa-lg"></i></a>
  <a id="menu-icon-tablet" href="#" aria-label="Menu"><i class="fas fa-bars fa-lg"></i></a>
  <a id="top-icon-tablet" href="#" aria-label="Top" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');" style="display:none;"><i class="fas fa-chevron-up fa-lg"></i></a>
  <span id="menu">
    <span id="nav">
      <ul>
        <!--
       --><li><a href="/">首页</a></li><!--
     --><!--
       --><li><a href="/tags/">标签</a></li><!--
     --><!--
       --><li><a href="/categories/">分类</a></li><!--
     --><!--
       --><li><a href="/archives/">归档</a></li><!--
     --><!--
       --><li><a target="_blank" rel="noopener" href="http://github.com/twitzz">项目</a></li><!--
     --><!--
       --><li><a href="/about/">关于</a></li><!--
     --><!--
       --><li><a href="/search/">搜索</a></li><!--
     -->
      </ul>
    </span>
    <br/>
    <span id="actions">
      <ul>
        
        <li><a class="icon" aria-label="上一篇" href="/2022/02/05/JavaScript/debounce/"><i class="fas fa-chevron-left" aria-hidden="true" onmouseover="$('#i-prev').toggle();" onmouseout="$('#i-prev').toggle();"></i></a></li>
        
        
        <li><a class="icon" aria-label="下一篇" href="/2022/02/05/JavaScript/ES6/"><i class="fas fa-chevron-right" aria-hidden="true" onmouseover="$('#i-next').toggle();" onmouseout="$('#i-next').toggle();"></i></a></li>
        
        <li><a class="icon" aria-label="返回顶部" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fas fa-chevron-up" aria-hidden="true" onmouseover="$('#i-top').toggle();" onmouseout="$('#i-top').toggle();"></i></a></li>
        <li><a class="icon" aria-label="分享文章" href="#"><i class="fas fa-share-alt" aria-hidden="true" onmouseover="$('#i-share').toggle();" onmouseout="$('#i-share').toggle();" onclick="$('#share').toggle();return false;"></i></a></li>
      </ul>
      <span id="i-prev" class="info" style="display:none;">上一篇</span>
      <span id="i-next" class="info" style="display:none;">下一篇</span>
      <span id="i-top" class="info" style="display:none;">返回顶部</span>
      <span id="i-share" class="info" style="display:none;">分享文章</span>
    </span>
    <br/>
    <div id="share" style="display: none">
      <ul>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.facebook.com/sharer.php?u=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/"><i class="fab fa-facebook " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://twitter.com/share?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/&text=Promise"><i class="fab fa-twitter " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.linkedin.com/shareArticle?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/&title=Promise"><i class="fab fa-linkedin " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://pinterest.com/pin/create/bookmarklet/?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/&is_video=false&description=Promise"><i class="fab fa-pinterest " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="mailto:?subject=Promise&body=Check out this article: https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/"><i class="fas fa-envelope " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://getpocket.com/save?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/&title=Promise"><i class="fab fa-get-pocket " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://reddit.com/submit?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/&title=Promise"><i class="fab fa-reddit " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.stumbleupon.com/submit?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/&title=Promise"><i class="fab fa-stumbleupon " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://digg.com/submit?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/&title=Promise"><i class="fab fa-digg " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.tumblr.com/share/link?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/&name=Promise&description="><i class="fab fa-tumblr " aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://news.ycombinator.com/submitlink?u=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/&t=Promise"><i class="fab fa-hacker-news " aria-hidden="true"></i></a></li>
</ul>

    </div>
    <div id="toc">
      <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B2%A1%E6%9C%89Promise%E5%89%8D%E9%81%87%E5%88%B0%E7%9A%84%E9%97%AE%E9%A2%98"><span class="toc-number">1.</span> <span class="toc-text">没有Promise前遇到的问题</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BD%91%E7%BB%9C%E8%AF%B7%E6%B1%82%E4%BD%BF%E7%94%A8%E7%9A%84%E9%97%AE%E9%A2%98"><span class="toc-number">1.1.</span> <span class="toc-text">网络请求使用的问题</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9B%9E%E8%B0%83%E5%9C%B0%E7%8B%B1%E7%9A%84%E9%97%AE%E9%A2%98"><span class="toc-number">1.2.</span> <span class="toc-text">回调地狱的问题</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise%E6%98%AF%E4%BB%80%E4%B9%88"><span class="toc-number">2.</span> <span class="toc-text">Promise是什么</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-%E7%9A%84%E7%8A%B6%E6%80%81"><span class="toc-number">3.</span> <span class="toc-text">Promise 的状态</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8Promise%E5%AF%B9%E8%AF%B7%E6%B1%82%E7%9A%84%E9%87%8D%E6%9E%84"><span class="toc-number">4.</span> <span class="toc-text">使用Promise对请求的重构</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#resolve"><span class="toc-number">5.</span> <span class="toc-text">resolve</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#reject"><span class="toc-number">6.</span> <span class="toc-text">reject</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#then"><span class="toc-number">7.</span> <span class="toc-text">then</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#then%E6%8E%A5%E6%94%B6%E7%9A%84%E5%8F%82%E6%95%B0"><span class="toc-number">7.1.</span> <span class="toc-text">then接收的参数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#then%E5%8F%AF%E4%BB%A5%E5%A4%9A%E6%AC%A1%E8%A2%AB%E8%B0%83%E7%94%A8"><span class="toc-number">7.2.</span> <span class="toc-text">then可以多次被调用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#then%E7%9A%84%E8%BF%94%E5%9B%9E%E5%80%BC"><span class="toc-number">7.3.</span> <span class="toc-text">then的返回值</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#catch"><span class="toc-number">8.</span> <span class="toc-text">catch</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#catch%E5%8F%AF%E4%BB%A5%E5%A4%9A%E6%AC%A1%E8%A2%AB%E8%B0%83%E7%94%A8"><span class="toc-number">8.1.</span> <span class="toc-text">catch可以多次被调用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#catch%E7%9A%84%E8%BF%94%E5%9B%9E%E5%80%BC"><span class="toc-number">8.2.</span> <span class="toc-text">catch的返回值</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#finally"><span class="toc-number">9.</span> <span class="toc-text">finally</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#all"><span class="toc-number">10.</span> <span class="toc-text">all</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#allSettled"><span class="toc-number">11.</span> <span class="toc-text">allSettled</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#race"><span class="toc-number">12.</span> <span class="toc-text">race</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%94%B9%E5%8F%98%E7%8A%B6%E6%80%81%E4%B8%8E%E6%8C%87%E5%AE%9A%E5%9B%9E%E8%B0%83%E7%9A%84%E9%A1%BA%E5%BA%8F%E6%89%A7%E8%A1%8C%E9%97%AE%E9%A2%98"><span class="toc-number">13.</span> <span class="toc-text">改变状态与指定回调的顺序执行问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise%E5%A6%82%E4%BD%95%E4%B8%B2%E8%81%94%E5%A4%9A%E4%B8%AA%E4%BB%BB%E5%8A%A1"><span class="toc-number">14.</span> <span class="toc-text">Promise如何串联多个任务</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise%E4%B8%AD%E7%9A%84%E5%BC%82%E5%B8%B8%E4%BC%A0%E9%80%8F"><span class="toc-number">15.</span> <span class="toc-text">Promise中的异常传透</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%AD%E6%96%ADpromise%E9%93%BE"><span class="toc-number">16.</span> <span class="toc-text">中断promise链</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#aysnc%E4%B8%8Eawait"><span class="toc-number">17.</span> <span class="toc-text">aysnc与await</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#async%E5%87%BD%E6%95%B0"><span class="toc-number">17.1.</span> <span class="toc-text">async函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#await%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="toc-number">17.2.</span> <span class="toc-text">await表达式</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%89%8B%E5%86%99Promise"><span class="toc-number">18.</span> <span class="toc-text">手写Promise</span></a></li></ol>
    </div>
  </span>
</div>

    
    <div class="content index py4">
        
        <article class="post" itemscope itemtype="http://schema.org/BlogPosting">
  <header>
    
    <h1 class="posttitle" itemprop="name headline">
        Promise
    </h1>



    <div class="meta">
      <span class="author" itemprop="author" itemscope itemtype="http://schema.org/Person">
        <span itemprop="name">柯里的语法糖</span>
      </span>
      
    <div class="postdate">
      
        <time datetime="2022-02-05T06:19:40.050Z" itemprop="datePublished">2022-02-05</time>
        
      
    </div>


      
    <div class="article-category">
        <i class="fas fa-archive"></i>
        <a class="category-link" href="/categories/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/">前端基础</a>
    </div>


      
    <div class="article-tag">
        <i class="fas fa-tag"></i>
        <a class="tag-link-link" href="/tags/JavaScript/" rel="tag">JavaScript</a>
    </div>


    </div>
  </header>
  

  <div class="content" itemprop="articleBody">
    <p>在研究一个 <code>Promise</code> 之前，我们先来看看没有 <code>Promise</code> 前，存在哪些技术痛点。</p>
<h2 id="没有Promise前遇到的问题"><a href="#没有Promise前遇到的问题" class="headerlink" title="没有Promise前遇到的问题"></a>没有Promise前遇到的问题</h2><h3 id="网络请求使用的问题"><a href="#网络请求使用的问题" class="headerlink" title="网络请求使用的问题"></a>网络请求使用的问题</h3><p>在没有出现 <code>Promise</code> 前，如果我们需要发送网络请求，需要封装并且调用这样的函数：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">request</span>(<span class="params">url, successCallback, failureCallback</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 模拟网络请求</span></span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> ((url = <span class="string">&#x27;curry&#x27;</span>)) &#123;</span><br><span class="line">      <span class="comment">// 发送成功了</span></span><br><span class="line">      successCallback()</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// 发送失败了</span></span><br><span class="line">      failureCallback()</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;, <span class="number">2000</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>虽然在上面的这种解决方案中，我们确实可以获得请求后函数的结果，但是它仍然存在几个问题：</p>
<ol>
<li>我们需要自己来设计回调函数、回调函数名称、回调函数使用。</li>
<li>对于不同的库或框架，开发出来的设计方案可能是不同的，我们只能通过看文档或者阅读文档等方式，去了解这个函数是怎么用的，这样的成本太大了。</li>
</ol>
<p><strong><code>Promise</code> 其实就是一种类似于规范的东西，规范了这种解决方案。</strong></p>
<h3 id="回调地狱的问题"><a href="#回调地狱的问题" class="headerlink" title="回调地狱的问题"></a>回调地狱的问题</h3><p>在发送 <code>ajax</code> 请求时，容易出现下面这样的，回调地狱的问题：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">$.ajax(<span class="string">&quot;url1&quot;</span>, <span class="function"><span class="keyword">function</span> (<span class="params">data1</span>) </span>&#123;</span><br><span class="line">        $.ajax(data1[<span class="string">&quot;url2&quot;</span>], <span class="function"><span class="keyword">function</span> (<span class="params">data2</span>) </span>&#123;</span><br><span class="line">          $.ajax(data2[<span class="string">&quot;url3&quot;</span>], <span class="function"><span class="keyword">function</span> (<span class="params">data3</span>) </span>&#123;</span><br><span class="line">            $.ajax(data3[<span class="string">&quot;url3&quot;</span>], <span class="function"><span class="keyword">function</span> (<span class="params">data4</span>) </span>&#123;</span><br><span class="line">              <span class="built_in">console</span>.log(data4);</span><br><span class="line">            &#125;);</span><br><span class="line">          &#125;);</span><br><span class="line">        &#125;);</span><br><span class="line">      &#125;);</span><br></pre></td></tr></table></figure>

<p>对于上面这种情况，正常时不会有什么问题的，但是这样的代码难看且不易维护，我们更加期望的是一种更加优雅的方式来进行异步操作。</p>
<p><strong><code>Promise</code> 可以以一种非常优雅的方式来解决这个问题。</strong></p>
<h2 id="Promise是什么"><a href="#Promise是什么" class="headerlink" title="Promise是什么"></a>Promise是什么</h2><p><code>Promise</code> 是一个类，当我们需要给予调用者一个承诺，待会我会给你回调数据时，就可以创建一个Promise的对象。</p>
<p>在通过 <code>new</code> 关键字创建 <code>Promise</code> 对象时，我们需要传入一个回调函数，称之为 <code>executor</code> 。</p>
<p>对于这个 <code>executor</code> 函数来说：</p>
<ul>
<li>它会立即执行，并且会接受两个参数，这两个参数是回调函数，分别称为 <code>resolve</code> 与 <code>reject</code> 。</li>
<li>当我们调用 <code>resolve</code> 回调函数时，会执行 <code>Promise</code> 实例对象的 <code>then</code> 方法中传入的回调函数。</li>
<li>当我们调用 <code>reject</code> 回调函数时，会执行 <code>Promise</code> 实例对象的 <code>catch</code> 方法传入的回调函数。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> p = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// resolve(&#x27;fulfilled status&#x27;)</span></span><br><span class="line">  <span class="comment">// reject(&#x27;rejected status&#x27;)</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">p.then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;res: &#x27;</span>, res)</span><br><span class="line">&#125;).catch(<span class="function"><span class="params">err</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;err: &#x27;</span>, err)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="Promise-的状态"><a href="#Promise-的状态" class="headerlink" title="Promise 的状态"></a>Promise 的状态</h2><p><code>Promise</code> 实例对象存在三个状态：</p>
<ul>
<li><code>pending</code> ： 初始状态，既没有被兑现，也没有被拒绝。（当执行 <code>executor</code> 中的代码时，处于该状态）</li>
<li><code>fulfilled</code> ：  意味着操作成功完成。（执行了 <code>resolve</code> 回调函数，处于该状态）</li>
<li><code>rejected</code> ： 意味着操作失败。（执行了 <code>reject</code> 回调函数或抛出异常，处于该状态）</li>
</ul>
<blockquote>
<p>一旦状态被确定下来，<code>Promise</code> 的状态会被<strong>锁死</strong>，该 <code>Promise</code> 的状态是不可更改的</p>
</blockquote>
<h2 id="使用Promise对请求的重构"><a href="#使用Promise对请求的重构" class="headerlink" title="使用Promise对请求的重构"></a>使用Promise对请求的重构</h2><p>有了 <code>Promise</code> 我们可以对之前网络请求的函数进行重构了。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">request</span>(<span class="params">url</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>) =&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">      <span class="keyword">if</span> ((url = <span class="string">&#x27;curry&#x27;</span>)) &#123;</span><br><span class="line">        <span class="comment">// 发送成功了</span></span><br><span class="line">        resolve()</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 发送失败了</span></span><br><span class="line">        reject()</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;,<span class="number">2000</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="resolve"><a href="#resolve" class="headerlink" title="resolve"></a>resolve</h2><p>我们来说明一下 <code>resolve</code> 中传入的不同参数的区别：</p>
<ol>
<li>如果传入的参数为 <code>Promise</code> 对象，则该 <code>Promise</code> 对象的结果决定了 <code>resolve</code> 的结果。</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  resolve(<span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    resolve(<span class="string">&#x27;fulfilled status&#x27;</span>)</span><br><span class="line">  &#125;))</span><br><span class="line">&#125;).then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;res: &#x27;</span>, res)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<ol start="2">
<li>如果传入的参数为 非<code>Promise</code> 类型的对象 则返回的结果为成功的 <code>promise</code> 对象。</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  resolve(<span class="string">&#x27;fulfilled status&#x27;</span>)</span><br><span class="line">&#125;).then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;res: &#x27;</span>, res)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<ol start="3">
<li>如果传入的参数为一个对象，并且这个对象有实现 <code>then</code> 方法（可以称为 <code>thenable</code> ），那么会执行该 <code>then</code> 方法，并且根据 <code>then</code> 方法的结果来决定 <code>Promise</code> 的状态。</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  resolve(&#123;</span><br><span class="line">    <span class="attr">then</span>:<span class="function"><span class="keyword">function</span>(<span class="params">resolve,reject</span>)</span>&#123;</span><br><span class="line">      resolve(<span class="string">&quot;fulfilled status&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;).then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;res: &#x27;</span>, res)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<blockquote>
<p>使用 <code>Promise</code> 静态方法中的 <code>resolve</code> 传参的使用相同</p>
</blockquote>
<h2 id="reject"><a href="#reject" class="headerlink" title="reject"></a>reject</h2><p>我们来说明一下 <code>reject</code> 中传入的不同参数的区别：</p>
<p>对于 <code>reject</code> 来说，无论传入什么值，返回的结果都是失败的 <code>Promise</code> 对象</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> p = <span class="built_in">Promise</span>.reject(<span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">() =&gt;</span> &#123;&#125;))</span><br><span class="line"></span><br><span class="line">p.then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&quot;res:&quot;</span>, res)</span><br><span class="line">&#125;).catch(<span class="function"><span class="params">err</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&quot;err:&quot;</span>, err) <span class="comment">// err: Promise &#123; &lt;pending&gt; &#125;</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="then"><a href="#then" class="headerlink" title="then"></a>then</h2><h3 id="then接收的参数"><a href="#then接收的参数" class="headerlink" title="then接收的参数"></a>then接收的参数</h3><p><code>then</code> 方法可以接受两个参数，用来处理成功的回调和失败的回调。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> p = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resovle, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// resovle()</span></span><br><span class="line">  <span class="comment">// reject()</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">p.then(</span><br><span class="line">  <span class="function"><span class="params">res</span> =&gt;</span> &#123;&#125;,</span><br><span class="line">  <span class="function"><span class="params">err</span> =&gt;</span> &#123;&#125;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 等价于</span></span><br><span class="line">p.then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">&#125;).catch(<span class="function"><span class="params">err</span> =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="then可以多次被调用"><a href="#then可以多次被调用" class="headerlink" title="then可以多次被调用"></a>then可以多次被调用</h3><p>一个 <code>Promise</code> 实例对象可以多次调用 <code>then</code> 方法，当我们的 <code>resolve</code> 方法被回调时, 所有的 <code>then</code> 方法传入的回调函数都会被调用：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">promise.then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&quot;res1:&quot;</span>, res)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">promise.then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&quot;res2:&quot;</span>, res)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">promise.then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&quot;res3:&quot;</span>, res)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="then的返回值"><a href="#then的返回值" class="headerlink" title="then的返回值"></a>then的返回值</h3><p><code>then</code> 方法返回一个 <code>Promise</code> 对象，所以我们可以进行链式调用：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">p.then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">&#125;).then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">&#125;).then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">&#125;).catch(<span class="function"><span class="params">err</span> =&gt;</span> &#123;</span><br><span class="line">  </span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>那么返回的 <code>Promise</code> 对象处于什么状态呢？有以下几种情况：</p>
<ol>
<li><p>当返回值为 <code>fulfilled</code> 状态的 <code>Promise</code> 、<code>fulfilled</code> 状态的 <code>thenable</code> 、普通的值时，它会处于 <code>fulfilled</code> 状态。</p>
</li>
<li><p>当返回值为 <code>rejected</code> 状态的 <code>Promise</code> 、 <code>then</code> 方法抛出异常、<code>rejected</code> 状态的 <code>thenable</code>，它会处于 <code>rejected</code> 状态。</p>
</li>
</ol>
<h2 id="catch"><a href="#catch" class="headerlink" title="catch"></a>catch</h2><h3 id="catch可以多次被调用"><a href="#catch可以多次被调用" class="headerlink" title="catch可以多次被调用"></a>catch可以多次被调用</h3><p>一个 <code>Promise</code> 实例对象的 <code>catch</code> 方法和 <code>then</code> 方法一样，也是可以多次调用的，每次调用我们都可以传入 <code>reject</code> 的回调函数，当 <code>Promise</code> 实例对象状态变为 <code>rejected</code> 的时候，这些函数都会被调用。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">promise.catch(<span class="function"><span class="params">err</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&quot;err1:&quot;</span>, err)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">promise.catch(<span class="function"><span class="params">err</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&quot;err2:&quot;</span>, err)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">promise.catch(<span class="function"><span class="params">err</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&quot;err3:&quot;</span>, err)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="catch的返回值"><a href="#catch的返回值" class="headerlink" title="catch的返回值"></a>catch的返回值</h3><p><code>catch</code> 方法和 <code>then</code> 方法同样，也会返回一个 <code>Promise</code> 对象，返回值的状态判断也和 <code>then</code> 方法一样。</p>
<p>如果我们需要后续继续执行 <code>catch</code> 方法中的回调函数，就需要返回一个 <code>rejected</code> 状态的 <code>Promise</code> 对象。</p>
<h2 id="finally"><a href="#finally" class="headerlink" title="finally"></a>finally</h2><p><code>finally</code> 方法表示：无论 <code>Promise</code> 对象无论变成 <code>fulfilled</code> 还是 <code>rejected</code> 状态，最终都会被执行的代码。</p>
<p>它不接收参数，只要之前的 <code>Promise</code> 对象处于非 <code>pending</code> 状态，那么它都会执行。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> p = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>) =&gt;</span> &#123;</span><br><span class="line">  resolve(<span class="string">&#x27;fulfilled status&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">p.then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>) =&gt;</span> &#123;</span><br><span class="line">    reject(<span class="string">&#x27;rejected status&#x27;</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;,<span class="function"><span class="params">err</span> =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">&#125;).then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">&#125;,<span class="function"><span class="params">err</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&quot;err: &quot;</span>,err)</span><br><span class="line">&#125;).finally(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&quot;finally&quot;</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="all"><a href="#all" class="headerlink" title="all"></a>all</h2><p><code>all</code> 方法接收一个包含 <code>Promise</code> 的数组。只要有一个 <code>Promise</code>对象的结果为 <code>rejected</code> 状态，那么返回的结果就为 <code>rejected</code> 状态的 <code>Promise</code>，否则它返回的结果是 <code>fulfilled</code> 状态的 <code>Promise</code> 对象 。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> p1 = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  resolve(<span class="string">&quot;OK&quot;</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">let</span> p2 = <span class="built_in">Promise</span>.resolve(<span class="string">&quot;success&quot;</span>)</span><br><span class="line"><span class="keyword">let</span> p3 = <span class="built_in">Promise</span>.resolve(<span class="string">&quot;oh yeah&quot;</span>)</span><br><span class="line"><span class="keyword">const</span> res = <span class="built_in">Promise</span>.all([p1, p2, p3])</span><br><span class="line"><span class="built_in">console</span>.log(res)</span><br></pre></td></tr></table></figure>

<h2 id="allSettled"><a href="#allSettled" class="headerlink" title="allSettled"></a>allSettled</h2><p><code>allSettled</code> 方法接收一个包含 <code>Promise</code> 的数组，等待所有 <code>Promise</code> 对象的状态确定，再根据顺序返回这个包含 <code>Promise</code> 对象的数组。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> p1 = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    resolve(<span class="number">11111</span>)</span><br><span class="line">  &#125;, <span class="number">1000</span>);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> p2 = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    reject(<span class="number">22222</span>)</span><br><span class="line">  &#125;, <span class="number">2000</span>);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> p3 = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    resolve(<span class="number">33333</span>)</span><br><span class="line">  &#125;, <span class="number">3000</span>);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="built_in">Promise</span>.allSettled([p1, p2, p3]).then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(res)</span><br><span class="line">&#125;).catch(<span class="function"><span class="params">err</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(err)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="race"><a href="#race" class="headerlink" title="race"></a>race</h2><p><code>race</code> 方法接收一个包含 <code>Promise</code> 的数组，返回一个新的 <code>Promise</code> 对象。其中，第一个确定状态的 <code>Promise</code> 对象的结果状态就是最终的结果状态</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> p1 = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    resolve(<span class="string">&quot;OK&quot;</span>)</span><br><span class="line">  &#125;, <span class="number">1000</span>);</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">let</span> p2 = <span class="built_in">Promise</span>.resolve(<span class="string">&quot;success&quot;</span>)</span><br><span class="line"><span class="keyword">const</span> res = <span class="built_in">Promise</span>.race([p1, p2, p3])</span><br><span class="line"><span class="built_in">console</span>.log(res)</span><br></pre></td></tr></table></figure>

<h2 id="改变状态与指定回调的顺序执行问题"><a href="#改变状态与指定回调的顺序执行问题" class="headerlink" title="改变状态与指定回调的顺序执行问题"></a>改变状态与指定回调的顺序执行问题</h2><ol>
<li>当执行器里面的任务为同步任务时，先该变 <code>Promise</code> 对应的状态 再指定回调。</li>
<li>当执行器里面的任务为异步任务时，先指定回调 再改变状态。</li>
<li>指定不是执行。</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> p = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    resolve(<span class="string">&quot;ok&quot;</span>)</span><br><span class="line">  &#125;, <span class="number">1000</span>);</span><br><span class="line">&#125;)</span><br><span class="line">p.then(<span class="function"><span class="params">value</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(value)</span><br><span class="line">&#125;, <span class="function"><span class="params">reason</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(reason)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p><code>then</code> 是微任务，定时器是宏任务。所以宏任务执行完后先去执行 <code>then</code>，也就是指定了<code>promise</code>改变状态时候的回调函数，然后再执行定时器，执行了<code>resolve(&quot;ok&quot;)</code>，触发<code>then</code>里面的回调。</p>
<h2 id="Promise如何串联多个任务"><a href="#Promise如何串联多个任务" class="headerlink" title="Promise如何串联多个任务"></a>Promise如何串联多个任务</h2><p>由于 <code>Promise</code> 中的 <code>then</code> 会返回 <code>Promise</code> 对象，因此使用链式调用将多个任务串联起来。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> p = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    resolve(<span class="string">&quot;ok&quot;</span>)</span><br><span class="line">  &#125;, <span class="number">1000</span>);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">p.then(<span class="function"><span class="params">value</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    resolve(<span class="string">&quot;success&quot;</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;).then(<span class="function"><span class="params">value</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(value)</span><br><span class="line">&#125;).then(<span class="function"><span class="params">value</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(value)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="Promise中的异常传透"><a href="#Promise中的异常传透" class="headerlink" title="Promise中的异常传透"></a>Promise中的异常传透</h2><p>当使用 <code>Promise</code> 的 <code>then</code> 链式调用时，可以在最后指定失败的回调前面任何操作出了异常，都会传到最后失败的回调中处理。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> p = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    resolve(<span class="string">&quot;ok&quot;</span>)</span><br><span class="line">    <span class="comment">// reject(&quot;error&quot;)</span></span><br><span class="line">  &#125;, <span class="number">1000</span>);</span><br><span class="line">&#125;)</span><br><span class="line">p.then(<span class="function"><span class="params">value</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// console.log(111)</span></span><br><span class="line">  <span class="keyword">throw</span> <span class="string">&quot;error&quot;</span></span><br><span class="line">&#125;).then(<span class="function"><span class="params">value</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="number">222</span>)</span><br><span class="line">&#125;).then(<span class="function"><span class="params">value</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="number">333</span>)</span><br><span class="line">&#125;).catch(<span class="function"><span class="params">reason</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(reason)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="中断promise链"><a href="#中断promise链" class="headerlink" title="中断promise链"></a>中断promise链</h2><p>有且只有一种方式，返回一个 <code>padding</code> 状态的 <code>Promise</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">p.then(<span class="function"><span class="params">value</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="number">111</span>)</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">() =&gt;</span> &#123; &#125;)</span><br><span class="line">&#125;).then(<span class="function"><span class="params">value</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="number">222</span>)</span><br><span class="line">&#125;).then(<span class="function"><span class="params">value</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="number">333</span>)</span><br><span class="line">&#125;).catch(<span class="function"><span class="params">reason</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(reason)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="aysnc与await"><a href="#aysnc与await" class="headerlink" title="aysnc与await"></a>aysnc与await</h2><h3 id="async函数"><a href="#async函数" class="headerlink" title="async函数"></a>async函数</h3><ol>
<li>函数的返回值是一个promise对象</li>
<li>promise对象的结果由async函数执行的返回值决定</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fn = <span class="keyword">async</span> <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    resolve()</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(fn())</span><br></pre></td></tr></table></figure>

<h3 id="await表达式"><a href="#await表达式" class="headerlink" title="await表达式"></a>await表达式</h3><ol>
<li>await右侧的表达式一般为promise对象，但也可以是其它的值</li>
<li>如果表达式是promise对象，await返回的是promise成功的值</li>
<li>如果await表达式返回的promise是失败的状态，则需要使用<code>try catch</code>捕获失败</li>
<li>如果表达式是其它值，直接将此值作为await的返回值</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fn = <span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="keyword">let</span> n = <span class="keyword">await</span> <span class="number">123</span></span><br><span class="line">    <span class="built_in">console</span>.log(n)<span class="comment">//123</span></span><br><span class="line">    <span class="keyword">let</span> p = <span class="keyword">await</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="comment">// resolve(&quot;ok&quot;)</span></span><br><span class="line">      reject(<span class="string">&quot;error&quot;</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(error)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">fn()</span><br></pre></td></tr></table></figure>

<h2 id="手写Promise"><a href="#手写Promise" class="headerlink" title="手写Promise"></a>手写Promise</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 声明构造函数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Promise</span>(<span class="params">executor</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 状态</span></span><br><span class="line">  <span class="built_in">this</span>.PromiseState = <span class="string">&quot;pending&quot;</span></span><br><span class="line">  <span class="comment">// 结果值</span></span><br><span class="line">  <span class="built_in">this</span>.PromiseResult = <span class="literal">null</span></span><br><span class="line">  <span class="comment">// 保存this值</span></span><br><span class="line">  <span class="keyword">const</span> self = <span class="built_in">this</span></span><br><span class="line">  <span class="built_in">this</span>.callbacks = []</span><br><span class="line">  <span class="comment">// resolve函数</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">resolve</span>(<span class="params">data</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// promise的状态只能被修改一次</span></span><br><span class="line">    <span class="keyword">if</span> (self.PromiseState !== <span class="string">&quot;pending&quot;</span>)</span><br><span class="line">      <span class="keyword">return</span></span><br><span class="line">    self.PromiseState = <span class="string">&quot;fulfilled&quot;</span></span><br><span class="line">    self.PromiseResult = data</span><br><span class="line">    <span class="comment">// 调用成功的回调</span></span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">      self.callbacks.forEach(<span class="function"><span class="params">item</span> =&gt;</span> &#123;</span><br><span class="line">        item.onResolved(data)</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// reject函数</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">reject</span>(<span class="params">data</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// promise的状态只能被修改一次</span></span><br><span class="line">    <span class="keyword">if</span> (self.PromiseState !== <span class="string">&quot;pending&quot;</span>)</span><br><span class="line">      <span class="keyword">return</span></span><br><span class="line">    self.PromiseState = <span class="string">&quot;rejected&quot;</span></span><br><span class="line">    self.PromiseResult = data</span><br><span class="line">    <span class="comment">// 调用成功的回调</span></span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">      self.callbacks.forEach(<span class="function"><span class="params">item</span> =&gt;</span> &#123;</span><br><span class="line">        item.onRejected(data)</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="comment">// 同步调用执行器函数</span></span><br><span class="line">    executor(resolve, reject)</span><br><span class="line">  &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">    <span class="comment">// promise的状态只能被修改一次</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">this</span>.PromiseState !== <span class="string">&quot;pending&quot;</span>)</span><br><span class="line">      <span class="keyword">return</span></span><br><span class="line">    <span class="built_in">this</span>.PromiseState = <span class="string">&quot;rejected&quot;</span></span><br><span class="line">    <span class="built_in">this</span>.PromiseResult = error</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 添加then方法</span></span><br><span class="line"><span class="built_in">Promise</span>.prototype.then = <span class="function"><span class="keyword">function</span> (<span class="params">onResolved, onRejected</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> self = <span class="built_in">this</span></span><br><span class="line">  <span class="comment">// 判断回调函数的参数</span></span><br><span class="line">  <span class="comment">// 保证异常传透</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> onRejected !== <span class="string">&quot;function&quot;</span>) &#123;</span><br><span class="line">    onRejected = <span class="function"><span class="params">reason</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">throw</span> reason</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 保证值传递</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> onResolved !== <span class="string">&quot;function&quot;</span>) &#123;</span><br><span class="line">    onResolved = <span class="function"><span class="params">value</span> =&gt;</span> value</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 封装函数</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">callback</span>(<span class="params">type</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> result = type(self.PromiseResult)</span><br><span class="line">        <span class="keyword">if</span> (result <span class="keyword">instanceof</span> <span class="built_in">Promise</span>) &#123;</span><br><span class="line">          result.then(<span class="function"><span class="params">v</span> =&gt;</span> &#123;</span><br><span class="line">            resolve(v)</span><br><span class="line">          &#125;, <span class="function"><span class="params">r</span> =&gt;</span> &#123;</span><br><span class="line">            reject(r)</span><br><span class="line">          &#125;)</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          resolve(result)</span><br><span class="line">        &#125;</span><br><span class="line">      &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">        reject(error)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// promise实例对象状态为fulfilled</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">this</span>.PromiseState === <span class="string">&quot;fulfilled&quot;</span>) &#123;</span><br><span class="line">      <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        callback(onResolved)</span><br><span class="line">      &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// promise实例对象状态为rejected</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">this</span>.PromiseState === <span class="string">&quot;rejected&quot;</span>) &#123;</span><br><span class="line">      <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        callback(onRejected)</span><br><span class="line">      &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// promise实例对象状态为pending</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">this</span>.PromiseState === <span class="string">&quot;pending&quot;</span>) &#123;</span><br><span class="line">      <span class="comment">// 保存then中传入的回调函数</span></span><br><span class="line">      <span class="built_in">this</span>.callbacks.push(&#123;</span><br><span class="line">        <span class="attr">onResolved</span>: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">          callback(onResolved)</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="attr">onRejected</span>: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">          callback(onRejected)</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  )</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 添加catch方法</span></span><br><span class="line"><span class="built_in">Promise</span>.prototype.catch = <span class="function"><span class="keyword">function</span> (<span class="params">onRejected</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">this</span>.then(<span class="literal">undefined</span>, onRejected)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 添加Promise.resolve方法</span></span><br><span class="line"><span class="built_in">Promise</span>.resolve = <span class="function"><span class="keyword">function</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (value <span class="keyword">instanceof</span> <span class="built_in">Promise</span>) &#123;</span><br><span class="line">      value.then(<span class="function"><span class="params">v</span> =&gt;</span> &#123;</span><br><span class="line">        resolve(v)</span><br><span class="line">      &#125;, <span class="function"><span class="params">r</span> =&gt;</span> &#123;</span><br><span class="line">        reject(r)</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      resolve(value)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 添加Promise.reject方法</span></span><br><span class="line"><span class="built_in">Promise</span>.reject = <span class="function"><span class="keyword">function</span> (<span class="params">reason</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    reject(reason)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 添加Promise.all方法</span></span><br><span class="line"><span class="built_in">Promise</span>.all = <span class="function"><span class="keyword">function</span> (<span class="params">promises</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">let</span> count = <span class="number">0</span></span><br><span class="line">    <span class="keyword">let</span> arr = []</span><br><span class="line">    promises.forEach(<span class="function">(<span class="params">item, index</span>) =&gt;</span> &#123;</span><br><span class="line">      item.then(<span class="function"><span class="params">v</span> =&gt;</span> &#123;</span><br><span class="line">        count++</span><br><span class="line">        arr[index] = v</span><br><span class="line">        <span class="keyword">if</span> (count === promises.length) &#123;</span><br><span class="line">          resolve(arr)</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;, <span class="function"><span class="params">r</span> =&gt;</span> &#123;</span><br><span class="line">        reject(r)</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 添加Promise.race方法</span></span><br><span class="line"><span class="built_in">Promise</span>.race = <span class="function"><span class="keyword">function</span> (<span class="params">promises</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    promises.forEach(<span class="function">(<span class="params">item</span>) =&gt;</span> &#123;</span><br><span class="line">      item.then(<span class="function"><span class="params">v</span> =&gt;</span> &#123;</span><br><span class="line">        resolve(v)</span><br><span class="line">      &#125;, <span class="function"><span class="params">r</span> =&gt;</span> &#123;</span><br><span class="line">        reject(r)</span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

  </div>
</article>



        
          <div id="footer-post-container">
  <div id="footer-post">

    <div id="nav-footer" style="display: none">
      <ul>
         
          <li><a href="/">首页</a></li>
         
          <li><a href="/tags/">标签</a></li>
         
          <li><a href="/categories/">分类</a></li>
         
          <li><a href="/archives/">归档</a></li>
         
          <li><a target="_blank" rel="noopener" href="http://github.com/twitzz">项目</a></li>
         
          <li><a href="/about/">关于</a></li>
         
          <li><a href="/search/">搜索</a></li>
        
      </ul>
    </div>

    <div id="toc-footer" style="display: none">
      <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B2%A1%E6%9C%89Promise%E5%89%8D%E9%81%87%E5%88%B0%E7%9A%84%E9%97%AE%E9%A2%98"><span class="toc-number">1.</span> <span class="toc-text">没有Promise前遇到的问题</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BD%91%E7%BB%9C%E8%AF%B7%E6%B1%82%E4%BD%BF%E7%94%A8%E7%9A%84%E9%97%AE%E9%A2%98"><span class="toc-number">1.1.</span> <span class="toc-text">网络请求使用的问题</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9B%9E%E8%B0%83%E5%9C%B0%E7%8B%B1%E7%9A%84%E9%97%AE%E9%A2%98"><span class="toc-number">1.2.</span> <span class="toc-text">回调地狱的问题</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise%E6%98%AF%E4%BB%80%E4%B9%88"><span class="toc-number">2.</span> <span class="toc-text">Promise是什么</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-%E7%9A%84%E7%8A%B6%E6%80%81"><span class="toc-number">3.</span> <span class="toc-text">Promise 的状态</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8Promise%E5%AF%B9%E8%AF%B7%E6%B1%82%E7%9A%84%E9%87%8D%E6%9E%84"><span class="toc-number">4.</span> <span class="toc-text">使用Promise对请求的重构</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#resolve"><span class="toc-number">5.</span> <span class="toc-text">resolve</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#reject"><span class="toc-number">6.</span> <span class="toc-text">reject</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#then"><span class="toc-number">7.</span> <span class="toc-text">then</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#then%E6%8E%A5%E6%94%B6%E7%9A%84%E5%8F%82%E6%95%B0"><span class="toc-number">7.1.</span> <span class="toc-text">then接收的参数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#then%E5%8F%AF%E4%BB%A5%E5%A4%9A%E6%AC%A1%E8%A2%AB%E8%B0%83%E7%94%A8"><span class="toc-number">7.2.</span> <span class="toc-text">then可以多次被调用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#then%E7%9A%84%E8%BF%94%E5%9B%9E%E5%80%BC"><span class="toc-number">7.3.</span> <span class="toc-text">then的返回值</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#catch"><span class="toc-number">8.</span> <span class="toc-text">catch</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#catch%E5%8F%AF%E4%BB%A5%E5%A4%9A%E6%AC%A1%E8%A2%AB%E8%B0%83%E7%94%A8"><span class="toc-number">8.1.</span> <span class="toc-text">catch可以多次被调用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#catch%E7%9A%84%E8%BF%94%E5%9B%9E%E5%80%BC"><span class="toc-number">8.2.</span> <span class="toc-text">catch的返回值</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#finally"><span class="toc-number">9.</span> <span class="toc-text">finally</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#all"><span class="toc-number">10.</span> <span class="toc-text">all</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#allSettled"><span class="toc-number">11.</span> <span class="toc-text">allSettled</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#race"><span class="toc-number">12.</span> <span class="toc-text">race</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%94%B9%E5%8F%98%E7%8A%B6%E6%80%81%E4%B8%8E%E6%8C%87%E5%AE%9A%E5%9B%9E%E8%B0%83%E7%9A%84%E9%A1%BA%E5%BA%8F%E6%89%A7%E8%A1%8C%E9%97%AE%E9%A2%98"><span class="toc-number">13.</span> <span class="toc-text">改变状态与指定回调的顺序执行问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise%E5%A6%82%E4%BD%95%E4%B8%B2%E8%81%94%E5%A4%9A%E4%B8%AA%E4%BB%BB%E5%8A%A1"><span class="toc-number">14.</span> <span class="toc-text">Promise如何串联多个任务</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise%E4%B8%AD%E7%9A%84%E5%BC%82%E5%B8%B8%E4%BC%A0%E9%80%8F"><span class="toc-number">15.</span> <span class="toc-text">Promise中的异常传透</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%AD%E6%96%ADpromise%E9%93%BE"><span class="toc-number">16.</span> <span class="toc-text">中断promise链</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#aysnc%E4%B8%8Eawait"><span class="toc-number">17.</span> <span class="toc-text">aysnc与await</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#async%E5%87%BD%E6%95%B0"><span class="toc-number">17.1.</span> <span class="toc-text">async函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#await%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="toc-number">17.2.</span> <span class="toc-text">await表达式</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%89%8B%E5%86%99Promise"><span class="toc-number">18.</span> <span class="toc-text">手写Promise</span></a></li></ol>
    </div>

    <div id="share-footer" style="display: none">
      <ul>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.facebook.com/sharer.php?u=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/"><i class="fab fa-facebook fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://twitter.com/share?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/&text=Promise"><i class="fab fa-twitter fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.linkedin.com/shareArticle?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/&title=Promise"><i class="fab fa-linkedin fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://pinterest.com/pin/create/bookmarklet/?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/&is_video=false&description=Promise"><i class="fab fa-pinterest fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="mailto:?subject=Promise&body=Check out this article: https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/"><i class="fas fa-envelope fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://getpocket.com/save?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/&title=Promise"><i class="fab fa-get-pocket fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://reddit.com/submit?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/&title=Promise"><i class="fab fa-reddit fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.stumbleupon.com/submit?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/&title=Promise"><i class="fab fa-stumbleupon fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://digg.com/submit?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/&title=Promise"><i class="fab fa-digg fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="http://www.tumblr.com/share/link?url=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/&name=Promise&description="><i class="fab fa-tumblr fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" target="_blank" rel="noopener" href="https://news.ycombinator.com/submitlink?u=https://danyuan30.gitee.io/2022/02/05/JavaScript/Promise/&t=Promise"><i class="fab fa-hacker-news fa-lg" aria-hidden="true"></i></a></li>
</ul>

    </div>

    <div id="actions-footer">
        <a id="menu" class="icon" href="#" onclick="$('#nav-footer').toggle();return false;"><i class="fas fa-bars fa-lg" aria-hidden="true"></i> 菜单</a>
        <a id="toc" class="icon" href="#" onclick="$('#toc-footer').toggle();return false;"><i class="fas fa-list fa-lg" aria-hidden="true"></i> 目录</a>
        <a id="share" class="icon" href="#" onclick="$('#share-footer').toggle();return false;"><i class="fas fa-share-alt fa-lg" aria-hidden="true"></i> 分享</a>
        <a id="top" style="display:none" class="icon" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fas fa-chevron-up fa-lg" aria-hidden="true"></i> 返回顶部</a>
    </div>

  </div>
</div>

        
        <footer id="footer">
  <div class="footer-left">
    Copyright &copy;
    
    
    2021-2022
    柯里的语法糖
  </div>
  <div class="footer-right">
    <nav>
      <ul>
        <!--
       --><li><a href="/">首页</a></li><!--
     --><!--
       --><li><a href="/tags/">标签</a></li><!--
     --><!--
       --><li><a href="/categories/">分类</a></li><!--
     --><!--
       --><li><a href="/archives/">归档</a></li><!--
     --><!--
       --><li><a target="_blank" rel="noopener" href="http://github.com/twitzz">项目</a></li><!--
     --><!--
       --><li><a href="/about/">关于</a></li><!--
     --><!--
       --><li><a href="/search/">搜索</a></li><!--
     -->
      </ul>
    </nav>
  </div>
</footer>

    </div>
    <!-- styles -->



  <link rel="preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" crossorigin="anonymous" onload="this.onload=null;this.rel='stylesheet'"/>


    <!-- jquery -->
 
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" crossorigin="anonymous"></script> 




<!-- clipboard -->

  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.7/clipboard.min.js" crossorigin="anonymous"></script> 
  
  <script type="text/javascript">
  $(function() {
    // copy-btn HTML
    var btn = "<span class=\"btn-copy tooltipped tooltipped-sw\" aria-label=\"复制到粘贴板!\">";
    btn += '<i class="far fa-clone"></i>';
    btn += '</span>'; 
    // mount it!
    $(".highlight table").before(btn);
    var clip = new ClipboardJS('.btn-copy', {
      text: function(trigger) {
        return Array.from(trigger.nextElementSibling.querySelectorAll('.code')).reduce((str,it)=>str+it.innerText+'\n','')
      }
    });
    clip.on('success', function(e) {
      e.trigger.setAttribute('aria-label', "复制成功!");
      e.clearSelection();
    })
  })
  </script>


<script src="/js/main.js"></script>

<!-- search -->

<!-- Google Analytics -->

<!-- Baidu Analytics -->

<!-- Cloudflare Analytics -->

<!-- Umami Analytics -->

<!-- Disqus Comments -->

<!-- utterances Comments -->

</body>
</html>
